<template>
  <div class="container">
    <div class="posts-page">
      <h1 class="page-title">文章</h1>
      <p class="page-description">这里是我的所有技术文章，主要关于前端、Java和全栈开发。</p>
      <div class="posts-filter">
        <div class="filter-header">
          <div class="search-bar">
            <input 
              type="text" 
              v-model="keyword" 
              placeholder="搜索文章..." 
              class="search-input"
              @keyup.enter="searchPost"
            />
          </div>
          <el-button 
            type="primary" 
            size="large" 
            @click="searchPost" 
            :loading="loading"
          >
            搜索
          </el-button>
          <router-link to="/posts/new" class="new-post-btn">
            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none"
              stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
              <line x1="12" y1="5" x2="12" y2="19"></line>
              <line x1="5" y1="12" x2="19" y2="12"></line>
            </svg>
            发布新文章
          </router-link>
        </div>
        <div class="filter-tags">
          <button v-for="tag in tagsList" :key="tag" :class="['filter-tag', selectedTags.includes(tag) ? 'active' : '']"
            @click="toggleTag(tag)">
            {{ tag.tagName }}
          </button>
        </div>
      </div>

      <el-empty v-if="!loading && postList.length === 0" description="暂无相关文章" />
      
      <div v-else class="posts-list">
        <el-skeleton v-if="loading" :rows="5" animated />
        <template v-else>
          <div v-for="post in postList" :key="post.id" class="post-item card">
            <router-link :to="`/posts/${post.id}`" class="post-item-link">
              <h2 class="post-item-title">{{ post.title }}</h2>
              <div class="post-item-meta">
                <span class="post-item-date">{{ post.createdTime }}</span>
                <span class="post-item-views">{{ post.views }} views</span>
              </div>
              <p class="post-item-excerpt">{{ post.summary }}</p>
              <div class="post-item-tags">
                <span v-for="tag in post.tagNames" :key="tag" class="post-item-tag">{{ tag }}</span>
              </div>
            </router-link>
          </div>
        </template>
      </div>
    </div>
    <div class="pagination-container">
      <el-pagination background layout="prev, pager, next, sizes,jumper, total" size="large" :total="total"
        v-model:current-page="pageParams.pageNum" v-model:page-size="pageParams.pageSize"
        :page-sizes="[5, 10, 20, 30, 40]" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>
  </div>
</template>
<script setup>
import { ref, onMounted, watch } from 'vue'
import { getPostList } from '../api/post.js'
import { getTagsList } from '../api/tags.js'
import { useRoute } from 'vue-router';
const route = useRoute();
const keyword = ref('')
const selectedTags = ref([])
const postList = ref([])
const tagsList = ref([])
const total = ref(0)
const pageCount = ref(0)
const pageParams = ref({
  pageNum: 1,
  pageSize: 10,
  keyword: undefined,
  tagsId: []
})
const loading = ref(false)

const fetchPosts = async () => {
  loading.value = true
  try {
    pageParams.value.tagsId = selectedTags.value.map(tag => tag.id)
    const res = await getPostList(pageParams.value)
    if (res.data) {
      postList.value = res.data.records
      total.value = res.data.total
      pageCount.value = res.data.pages
      pageParams.value.pageNum = res.data.current
      pageParams.value.pageSize = res.data.size
    }
  } catch (error) {
    console.error('Failed to fetch posts:', error)
  } finally {
    loading.value = false
  }
}

const fetchTags = async () => {
  const res = await getTagsList({ pageNum: 1, pageSize: 1000, name: '', isAll: true })
  if (res.data) {
    tagsList.value = res.data.records
    // 获取到标签列表后，检查 URL 参数
    const tagId = route.query.tagId
    if (tagId) {
      const selectedTag = tagsList.value.find(tag => tag.id === Number(tagId))
      if (selectedTag && !selectedTags.value.find(t => t.id === selectedTag.id)) {
        selectedTags.value = [selectedTag] // 重置选中的标签
        pageParams.value.tagsId = [selectedTag.id]
        fetchPosts() // 重新获取文章列表
      }
    }
  }
}

onMounted(() => {
  fetchTags() // 先获取标签列表
  fetchPosts()
})

// 移除旧的 watch，改为监听整个 route 对象
watch(() => route.query, (newQuery) => {
  if (newQuery.tagId && tagsList.value.length > 0) {
    const selectedTag = tagsList.value.find(tag => tag.id === Number(newQuery.tagId))
    if (selectedTag && !selectedTags.value.find(t => t.id === selectedTag.id)) {
      selectedTags.value = [selectedTag]
      pageParams.value.tagsId = [selectedTag.id]
      fetchPosts()
    }
  }
})

const handleSizeChange = (val) => {
  pageParams.value.pageSize = val
  fetchPosts()
}

const handleCurrentChange = (val) => {
  pageParams.value.pageNum = val
  fetchPosts()
}

const searchPost = () => {
  pageParams.value.keyword = keyword.value
  pageParams.value.pageNum = 1
  fetchPosts()
}

const toggleTag = (tag) => {
  const index = selectedTags.value.indexOf(tag)
  if (index > -1) {
    selectedTags.value.splice(index, 1)
  } else {
    selectedTags.value.push(tag)
  }
  pageParams.value.pageNum = 1
  fetchPosts()
}
</script>
<style scoped>
.posts-page {
  padding: 2rem 0;
  text-align: left;
}

.page-title {
  font-size: 2.5rem;
  margin-bottom: 0.5rem;
}

.page-description {
  font-size: 1.125rem;
  margin-bottom: 2rem;
  color: #555;
}

.posts-filter {
  margin-bottom: 2.5rem;
  max-width: 1200px;
  margin-left: auto;
  margin-right: auto;
  /* padding: 1.5rem; */
  background-color: var(--color-background-soft);
  border-radius: 8px;
}

.filter-header {
  display: flex;
  gap: 1rem;
  margin-bottom: 1.5rem;
  align-items: center;
  max-width: 100%;
  justify-content: flex-start;
}

.search-bar {
  flex: 1;
  max-width: 600px;
}

.search-input {
  width: 100%;
  height: 44px;
  padding: 0 16px;
  font-size: 15px;
  border: 1px solid var(--el-border-color);
  border-radius: 8px;
  background-color: var(--color-background);
  color: var(--color-text);
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.search-input:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  border-color: var(--el-border-color-hover);
}

.search-input:focus {
  outline: none;
  border-color: var(--el-color-primary);
  box-shadow: 0 4px 12px rgba(var(--el-color-primary-rgb), 0.15);
}

.search-input::placeholder {
  color: var(--color-text-light);
}

.filter-header .el-button {
  flex-shrink: 0;
  height: 44px;
  padding: 0 20px;
  font-size: 15px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.filter-header .el-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.new-post-btn {
  flex-shrink: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.4rem;
  padding: 0.5rem 1rem;
  background-color: var(--color-primary);
  color: white;
  border-radius: 6px;
  font-weight: 500;
  font-size: 0.9rem;
  transition: all 0.3s ease;
  margin-left: 1rem;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.new-post-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.new-post-btn svg {
  width: 14px; /* Smaller icon */
  height: 14px;
}

.filter-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
  justify-content: flex-start;
}

.filter-tag {
  background-color: #f3f4f6;
  border: 1px solid transparent;
  border-radius: 20px;
  padding: 0.5rem 1rem;
  font-size: 0.875rem;
  cursor: pointer;
  transition: all 0.3s ease;
  font-weight: 500;
}

.filter-tag:hover {
  background-color: #e4e9f0;
  transform: translateY(-2px);
}

.filter-tag.active {
  background-color: var(--color-primary);
  color: white;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.posts-list {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
  max-width: 1200px;
  margin-left: auto;
  margin-right: auto;
}

.post-item {
  transition: transform 0.2s, box-shadow 0.2s;
  text-align: left;
}

.post-item:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.post-item-link {
  display: block;
  color: var(--color-text);
}

.post-item-link:hover {
  text-decoration: none;
}

.post-item-title {
  font-size: 1.5rem;
  margin-bottom: 0.5rem;
}

.post-item-meta {
  display: flex;
  justify-content: space-between;
  font-size: 0.875rem;
  color: #666;
  margin-bottom: 0.75rem;
}

.post-item-excerpt {
  font-size: 1rem;
  margin-bottom: 1rem;
  color: #444;
}

.post-item-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 0.6rem;
  margin-top: 1.2rem;
}

.post-item-tag {
  padding: 0.3rem 0.8rem;
  background-color: #f3f4f6;
  border-radius: 20px;
  font-size: 0.8rem;
  color: var(--color-primary);
  transition: all 0.2s ease;
  border: 1px solid transparent;
}

.post-item-tag:hover {
  background-color: var(--color-primary);
  color: white;
  transform: translateY(-2px);
}

@media (max-width: 768px) {
  
  
  .filter-header {
    flex-direction: column;
    gap: 0.75rem;
  }
  
  .search-bar {
    width: 100%;
  }
  
  .filter-header .el-button,
  .new-post-btn {
    width: 100%;
    margin-left: 0;
  }
  
  .filter-tags {
    justify-content: flex-start;
    padding: 0 0.5rem;
  }
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin: 2rem 0;
}
</style>
